<?php
/**
 * Created by Sublime.
 * User: banjin
 * Date: 17-1-23
 * Time: 上午10:04
 */
namespace app\backend\model;

use think\Model;

class Lease extends Model
{
    private $contractTable    = 'z_contract_order';
    private $buildingTable    = 'z_building';
    private $houseTable       = 'z_house';
    private $contractFeeTable = 'z_contract_fee';
    private $contractExtTable = 'z_contract_order_ext';
    public function __construct() {
        parent::__construct();
    }

    /**
     * 获取我的合同
     * @date   2017-01-18
     * @author wuhao
     *
     * @param  int  $mid   用户id
     * @param  int  $dtype 用户类型
     * @param  int  $page  页数
     * @param  int  $pageSize  每页个数
     *
     * @return array
     */
    public function getMyLease($mid, $dtype, $page = 1, $pageSize = 10)
    {
        if (!$mid || !$page ||!$pageSize) {
            return false;
        }

        if ($dtype === 0) {//管理员查询所有
            $where = [];
        } elseif (in_array($dtype, [3, 4])) {
            //|f.owner_id'
            $where['create_user|owner_id'] =  $mid;
        } elseif ($dtype == 2) {
            //租户
            $where['tenant_id'] = $mid;
        } elseif ($dtype == 1) {
            //业主
            $where['owner_id']  = $mid;
        }

        $where['status'] = 1;
        $field = 'id, ordernum, building_id, tenant_id, begin_time,end_time, status, industry, ordermode';

        $res =  $this->setTable($this->contractTable)->field($field)
            ->where($where)->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }
        $sum   = $this->setTable($this->contractTable)->where($where)->count();
        $total = ceil($sum / $pageSize);
        $data = ['list' => $res, 'total' => $total, 'current_page' => $page];
        return $data;
    }

    /**
     * 根据合同编号查看合同具体内容
     * @author wuhao
     * @date   2017-4-13
     *
     * @param  $ordernum  int  合同编号
     * @return
     */
    public function getLeaseDetail($ordernum)
    {
        if (!$ordernum) {
            return false;
        }

        $where = [
            'ordernum' => $ordernum
        ];

        $field = "ordernum, building_id, ordermode, industry, tenant_id, begin_time, end_time, charge_type, legal_id_card,finance_mobile,finance_user,
         tax, billing_day, growth_rate, discount, contract_time";
        $res = $this->table($this->contractTable)->where($where)->field($field)->find();
        return $res ?: [];
    }

    /**
     * 未生效的合约 删除收费分成比例
     * @date   2016-01-23
     * @author banjin
     * @param  $id  int  收费比例id
     *
     * @return
     */
    public function delContractFee($id)
    {
        $where = [
            'id' => $id
        ];

        return $this->table($this->contractFeeTable)->where($where)->delete();
    }


    /**
     * 录入合约
     * @date   2017-01-24
     * @author banjin
     *
     * @param  $data array  合约信息
     * @return
     */
    public function insertContractInfo($data)
    {
        return $this->setTable($this->contractTable)->insertGetId($data);
    }

    /**
     * 录入合约费用
     * @date 2017-02-04
     * @author banjin
     *
     * @param  $data array  合约费用信息
     * @return
     */
    public function insertFeeInfo($data)
    {
        return $this->setTable($this->contractFeeTable)->insertAll($data);
    }

    /**
     * 批量录入合约拓展表信息
     * @date 2017-04-11
     * @author wuhao
     *
     * @param   array $data  合约拓展信息
     * @return
     */
    public function insertExtInfo($data)
    {
        return $this->setTable($this->contractExtTable)->insertAll($data);
    }

    /**
     * 根据房源编号或房源编号数组获取对应的生效的租赁签约拓展信息
     * @date 2017-04-12
     * @author wuhao
     *
     * @param   int|array $houseNumber  房源编号或其数组
     * @param   string    $field        要查询的字段
     * @return array
     */
    public function getLeaseExtByHouse($houseNumber, $field = '*')
    {
        if (!$houseNumber || (!is_numeric($houseNumber) && !is_array($houseNumber))) {
            return false;
        }
        $this->setTable($this->contractExtTable)->field($field);
        if (is_array($houseNumber)) {
            $res = $this->where(['house_number' => ['in', $houseNumber], 'status' => 1])->select();
        } else {
            $res = $this->where(['house_number' => $houseNumber, 'status' => 1])->find();
        }
        return $res ?: [];
    }


    /**
     * 根据房源编号或房源编号数组获取对应的生效的租赁签约拓展信息
     * @date 2017-05-26
     * @author wuhao
     *
     * @param   string|array $room         房号信息
     * @param   string       $field        要查询的字段
     * @param   int          $status       状态 0=失效 1=生效 2=未生成账单
     * @return array
     */
    public function getLeaseExtByRoom($room, $field = '*', $status = 1)
    {
        if (!$room || (!is_numeric($room) && !is_array($room))) {
            return false;
        }
        $this->setTable($this->contractExtTable)->field($field);
        if (is_array($room)) {
            $res = $this->where(['room' => ['in', $room], 'status' => $status])->select();
        } else {
            $res = $this->where(['room' => $room, 'status' => $status])->select();
        }
        return $res ?: [];
    }

    /**
     * 获取单个房源信息
     * @date   2017-12-30
     * @author banjin
     *
     * @param  string  $field    数据字段
     * @param  array   $where    查询条件
     *
     * @return
     */
    public function getHouseInfo($field, $where, $limit)
    {
        return $this->setTable($this->houseTable. ' h')
               ->join($this->buildingTable. ' b', 'h.building_id=b.id', 'LEFT')
                ->field($field)->where($where)->limit($limit)->select();
    }

    /**
     * 获取租赁签约房源信息
     * @date   2017-5-5
     * @author wuhao
     *
     * @param  string  $field    数据字段
     * @param  array   $where    查询条件
     * @param  int     $memberId 用户id
     * @param  array   $trustHouse     托管的房源id数组
     * @param  int     $page   页数
     * @param  int     $pageSize   每页个数
     *
     * @return array|bool
     */
    public function getLeaseHouse($field, $where, $memberId, $trustHouse, $page = 1, $pageSize = 10)
    {
        if (!$field || !$where || !$memberId) {
            return false;
        }
        $map = '';
        if ($trustHouse) {
            $trustHouse = '('. implode(',', $trustHouse). ')';
            $map = "(h.mid = $memberId) OR (h.id in $trustHouse)";
        } else {
            $map = "h.mid = $memberId";
        }
        $res =  $this->setTable($this->houseTable. ' h')
            ->join($this->buildingTable. ' b', 'h.building_id=b.id', 'LEFT')
            ->field($field)->where($where)->where($map)->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }
        $sum = $this->setTable($this->houseTable. ' h')
            ->join($this->buildingTable. ' b', 'h.building_id=b.id', 'LEFT')
            ->where($where)->where($map)->count();
        $data = [
            'page' => $page,
            'list' => $res,
            'totalnum' => $sum,
            'totalpage' => ceil($sum / $pageSize),
        ];
        return $data;
    }

    /**
     * 获取单个房源信息总数
     * @date   2017-01-12
     * @author banjin
     *
     * @param  string  $field    数据字段
     * @param  array   $where    查询条件
     *
     * @return
     */
    public function getHouseInfoCnt($where)
    {
        return $this->setTable($this->houseTable. ' h')
            ->join($this->buildingTable. ' b', 'h.building_id=b.id', 'LEFT')
            ->where($where)->count();
    }

    /**
     * 使合约失效
     * @date   2017-4-5
     * @author wuhao
     *
     * @param  string  $ordernum    合同编号
     * @param  int     $status      合约状态 1=生效 0=失效
     *
     * @return
     */
    public function forbidLease($ordernum, $status)
    {
        if (!$ordernum || !in_array($status, [0, 1])) {
            return false;
        }
        $data  = ['status' => $status];
        $where = ['ordernum' => $ordernum];
        return $this->setTable($this->contractTable)->where($where)->update($data);
    }

    /**
     * 使拓展表合约失效
     * @date   2017-4-13
     * @author wuhao
     *
     * @param  string  $ordernum    合同编号
     * @param  int     $status      合约状态 1=生效 0=失效
     *
     * @return
     */
    public function forbidExtLease($ordernum, $status)
    {
        if (!$ordernum || !in_array($status, [0, 1])) {
            return false;
        }
        $data  = ['status' => $status, 'update_time' => time()];
        $where = ['ordernum' => $ordernum];
        return $this->setTable($this->contractExtTable)->where($where)->update($data);
    }

    /**
     * 获取合约信息
     * @date   2017-4-5
     * @author wuhao
     *
     * @param  array  $where    条件
     * @param  string $field    获取的字段
     *
     * @return
     */
    public function getContractInfo($where, $field = '*')
    {
        if (!$where || !is_array($where) || !$field) {
            return false;
        }

        return $this->setTable($this->contractTable)->field($field)->where($where)->select();
    }

    /**
     * 根据合同编号获取合约基本信息
     * @date   2017-4-12
     * @author wuhao
     *
     * @param  int|array    $orderNum    合同编号
     * @param  string       $field       获取的字段
     *
     * @return array|bool
     */
    public function getLeaseByOrderNum($orderNum, $field = '*')
    {
        if (!$orderNum || (!is_numeric($orderNum) && !is_array($orderNum))) {
            return false;
        }
        if (is_array($orderNum)) {
            $where = ['ordernum' => ['in', $orderNum], 'status' => 1];
            $res = $this->setTable($this->contractTable)->field($field)->where($where)->select();
        } else {
            $where = ['ordernum' => $orderNum, 'status' => 1];
            $res = $this->setTable($this->contractTable)->field($field)->where($where)->find();
        }

        return $res ?: [];
    }

    /**
     * 根据合同编号获取合约拓展表信息
     * @date   2017-4-12
     * @author wuhao
     *
     * @param  int|array    $orderNum  合同编号或其数组
     * @param  string       $field     获取的字段
     *
     * @return array|bool
     */
    public function getLeaseExtByOrderNum($orderNum, $field = '*')
    {
        if (!$orderNum || (!is_numeric($orderNum) && !is_array($orderNum))) {
            return false;
        }
        $this->setTable($this->contractExtTable)->field($field);
        if (is_array($orderNum)) {
            $where = ['ordernum' => ['in', $orderNum], 'status' => 1];
            $res = $this->where($where)->select();
        } else {
            $where = ['ordernum' =>  $orderNum, 'status' => 1];
            $res = $this->where($where)->select();
        }

        return $res ?: [];
    }

    /**
     * 根据合同编号获取合约的费用详情信息
     * @date   2017-4-12
     * @author wuhao
     *
     * @param  int    $ordernum    条件
     * @param  string $field       获取的字段
     *
     * @return
     */
    public function getLeaseFeeByOrderNum($orderNum, $field = '*')
    {
        if (!$orderNum || !is_numeric($orderNum)) {
            return false;
        }
        $where = ['ordernum' => $orderNum];
        return $this->setTable($this->contractFeeTable)->field($field)->where($where)->select();
    }

    /**
     * 根据合同编号获取合约的房租，物业费的收款人，收款比例，收款金额类型
     * @date   2017-4-12
     * @author wuhao
     *
     * @param  int    $ordernum    条件
     * @param  string $field       获取的字段
     *
     * @return
     */
/*    public function getLeaseFeeOwner($orderNum)
    {
        if (!$orderNum || !is_numeric($orderNum)) {
            return false;
        }
        $where = ['ordernum' => $orderNum, 'type' => ['in', [1, 2]]];
        $field = 'distinct owner_id, type, ratio';
        return $this->setTable($this->contractFeeTable)->field($field)->where($where)->select();
    }*/

    /**
     * 获取进行中的合同信息
     * @date   2017-01-19
     * @author Lanlc
     *
     *
     * @return
     */
    public function getRunningContract($where, $page = 1, $pageSize, $field = 'id, ordernum, end_time')
    {
        $offSet = ($page-1)*$pageSize;
        return $this->setTable($this->contractTable)->field($field)->where($where)->limit($offSet, $pageSize)->select();
    }


    /**
     * 更新失效合同
     * @date   2017-01-16
     * @author Lanlc
     *
     * @param  int  $ContractId  合同ID
     *
     * @return
     */
    public function updateContract($where, $data)
    {
        return $this->table($this->contractTable)->where($where)->update($data);
    }

    /**
     * 更新失效合同
     * @date   2017-01-16
     * @author Lanlc
     *
     * @param  int  $ContractId  合同ID
     *
     * @return
     */
    public function updateContractExt($where, $data)
    {
        return $this->table($this->contractExtTable)->where($where)->update($data);
    }

    /**
     * 获取合同收费项目信息
     * @date   2017-01-17
     * @author Lanlc
     *
     *
     * @return
     */
    public function getContractFee($where, $field = '*')
    {
        return $this->setTable($this->contractFeeTable)->field($field)->where($where)->select();
    }

    /**
     * 由id来获取合同基本信息
     * @date   2017-04-19
     * @author wuhao
     *
     * @param int     $id   收费对象
     * @return array
     */
    public function getLeaseById($id)
    {
        if (!is_numeric($id) || $id <=0) {
            return false;
        }
        $where = ['id' => $id];
        return $this->setTable($this->contractTable)->where($where)->find();
    }

    /**
     * 更新合同信息
     * @date   2017-05-15
     * @author wuhao
     *
     * @param int  $ordernum  订单号
     * @param string  $financeUser  财务联系人姓名
     * @param string  $financeMobile  财务联系人电话
     * @return bool
     */
    public function updateLease($ordernum, $financeUser, $financeMobile)
    {
        if (!$ordernum || !$financeMobile || !$financeUser) {
            return  false;
        }
        $where = ['ordernum' => $ordernum];
        $data = [
            'finance_user' => $financeUser,
            'finance_mobile' => $financeMobile,
        ];
        return $this->setTable($this->contractTable)->where($where)->update($data);
    }

    /**
     * 获取导入的合同列表
     * @date   2017-06-28
     * @author wuhao
     *
     * @param array  $buildId   楼宇id数组
     * @param string $room      房号
     * @param int    $memberId  用户id
     * @param int    $page
     * @param int    $pageSize

     * @return array
     */
    public function getImportOrder($buildId = [], $room = '', $memberId, $page = 1, $pageSize = 15)
    {
        if (!$memberId || !$page || !$pageSize) {
            return false;
        }
        $where['c.owner_id'] = $memberId;
        if ($buildId) {
            $where['c.building_id'] = ['in', $buildId];
        }
        if ($room) {
            $where['e.ordernum'] = $room;
        }
        $where['c.status'] = 2;
        $field = 'c.building_id, c.ordernum, c.tenant_id, e.house_number, e.number, e.room';

        $res = $this->table($this->contractTable.' c')->field($field)
            ->join($this->contractExtTable. ' e', 'c.ordernum=e.ordernum', 'LEFT')->where($where)->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        } else {
            $sum = $this->table($this->contractTable.' c')->field($field)
                ->join($this->contractExtTable. ' e', 'c.ordernum=e.ordernum', 'LEFT')->where($where)->count();
            $total = ceil($sum / $pageSize);
            return [
                'total' => $total,
                'list'  => $res,
            ];
        }
    }

    /**
     * 获取导入的合同列表
     * @date   2017-06-28
     * @author wuhao
     *
     * @param string $ordernum  合同编号
     * @return array
     */
    public function getImportOrderDetail($ordernum)
    {
        if (!$ordernum) {
            return false;
        }
        $where = [
            'c.ordernum' => $ordernum,
            'c.status'   => 2,
        ];
        $field = 'c.id, c.ordernum, c.tenant_id, c.owner_id, c.building_id, c.begin_time, c.end_time, c.finance_mobile,
        c.charge_type, c.free_day,  c.billing_day, e.house_number, e.room';
        return $this->table($this->contractTable.' c')->field($field)
            ->join($this->contractExtTable. ' e', 'c.ordernum=e.ordernum', 'LEFT')->where($where)->find();
    }
}
